package com.gblw.rjkf.pj.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblw.rjkf.pj.entity.SysUser;
import com.gblw.rjkf.pj.entity.SysUserSign;
import com.gblw.rjkf.pj.mapper.SysUserMapper;
import com.gblw.rjkf.pj.mapper.SysUserSignMapper;
import com.gblw.rjkf.pj.service.SysRoleService;
import com.gblw.rjkf.pj.service.SysUserService;
import com.gblw.rjkf.pj.utils.Result;
import com.gblw.rjkf.pj.utils.sm.SMConfig;
import com.gblw.rjkf.pj.utils.sm.Sm2Util;
import com.gblw.rjkf.pj.utils.sm.Sm4Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2024-08-13 15:24:44
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserSignMapper sysUserSignMapper;
    @Resource
    SysRoleService sysRoleService;
    @Override
    public Result page(Integer pageNum, Integer pageSize, String userName, String nickName) {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(SysUser.class, i -> !i.getProperty().equals("password")); //不查询password字段
        // 判断 user_name 是否有值，如果有值则添加到查询条件中
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.eq("user_name", userName);
        }
        // 判断 nick_name 是否有值，如果有值则添加到查询条件中
        if (StringUtils.isNotBlank(nickName)) {
            queryWrapper.eq("nick_name", nickName);
        }
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        IPage<SysUser> pageList = sysUserMapper.selectPage(page, queryWrapper);
        return Result.success("查询成功", pageList);
    }

    @Override
    public Result insertUser(SysUser sysUser) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", sysUser.getUserName());
        List<SysUser> list = baseMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            //系统级解密
            String password = Sm2Util.decrypt(SMConfig.privateKey, sysUser.getPassword());
            Map<String, String> keymap = Sm2Util.generator();
            String publicKey = keymap.get("publicKey");
            String privateKey = keymap.get("privateKey");
            SysUser sysUser1 = new SysUser();
            String key = publicKey.substring(0, 16);
            sysUser1.setPassword(Sm4Util.encrypt(key, password));
            sysUser1.setNickName(sysUser.getNickName());
            sysUser1.setUserName(sysUser.getUserName());
            sysUser1.setHeadPortrait(sysUser.getHeadPortrait());
            int setUid = sysUserMapper.insert(sysUser1);
            SysUserSign sysUserSign = new SysUserSign();
            sysUserSign.setUid(sysUser1.getId());
            sysUserSign.setPublicKey(publicKey);
            sysUserSign.setSecretKey(privateKey);
            sysUserSignMapper.insert(sysUserSign);
            return Result.success("添加成功", "");
        }
        return Result.error("账号已经存在");
    }

    @Override
    public Result getUserSign(SysUser sysUser) {
        SysUser result = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_name", sysUser.getUserName()));
        if (result != null) {
            SysUserSign sysUserSign = sysUserSignMapper.selectOne(new QueryWrapper<SysUserSign>().eq("uid", result.getId()));
            if (sysUserSign != null) {
                String key = sysUserSign.getPublicKey().substring(0, 16);
                if (result.getPassword().equals(Sm4Util.encrypt(key, Sm2Util.decrypt(SMConfig.privateKey, sysUser.getPassword())))) {
                    StpUtil.login(result.getId(), "Admin");
                    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                    JSONObject map = new JSONObject();
                    map.put("nickName", result.getNickName());
                    map.put("headPortrait", result.getHeadPortrait());
                    tokenInfo.setTag(map.toString());
                    sysRoleService.getRoleList();
                    sysRoleService.cachedPermissions();
                    return Result.success("登录成功", tokenInfo);
                } else {
                    return Result.error("密码错误");
                }

            } else {
                return Result.error("请联系管理员");
            }
        } else {
            return Result.error("账号不存在。。。");
        }

    }

    @Override
    public Result updateUser(SysUser sysUser) {
        String password = Sm2Util.decrypt(SMConfig.privateKey, sysUser.getPassword());
        QueryWrapper<SysUserSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", sysUser.getId());
        SysUserSign sysUserSign = sysUserSignMapper.selectOne(queryWrapper);
        Map<String, String> keymap = Sm2Util.generator();
        String publicKey = sysUserSign.getPublicKey().substring(0, 16);
        SysUser sysUser1 = new SysUser();
        sysUser1.setPassword(Sm4Util.encrypt(publicKey, password));
        sysUser1.setNickName(sysUser.getNickName());
        sysUser1.setHeadPortrait(sysUser.getHeadPortrait());
        baseMapper.insert(sysUser1);
        return  Result.success("修改成功","");
    }

    @Override
    public Result deleteUser(Integer id) {
        SysUser sysUser = baseMapper.selectById(id);
        if (sysUser == null) {
            return Result.success("已经删除", "");
        } else if (sysUser.getUserName().equals("admin")) {
            return Result.error("傻逼，你是怎么进来的");
        } else {
            baseMapper.deleteById(id);
           return Result.success("已经删除", "");
        }
    }
}

